import os
import cv2
import argparse


def readFile(_path):
    # 读取出的队列
    _info_list = []
    title_tmp = None
    with open(_path, 'r', encoding='utf-8') as f:
        for line in f:
            # line = line[:-1]  # 去掉换行符
            if line.startswith("#EXTINF:-1"):
                title_tmp = line
            else:
                # find url
                if title_tmp is not None:
                    _info_list.append([title_tmp, line])
                    title_tmp = None
    return _info_list


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="StreamPlayer")
    parser.add_argument("--source", default="../../source/Kodi/m3u_test.txt", type=str)
    args = parser.parse_args()

    # 使用opencv Resize会导致视频流卡顿
    tv_size = None
    # tv_size = [640, 360]

    # 输入文件检查
    if not os.path.exists(args.source):
        exit(-1)

    # 读取直播源列表
    info_list = readFile(args.source)

    website = info_list[0][1]

    cap = cv2.VideoCapture(website)
    ret, frame = cap.read()
    if ret:
        print("即将开始播放，按“‘q’键位退出")
    while ret:
        ret, frame = cap.read()
        if tv_size is not None:
            frame = cv2.resize(frame, tv_size, interpolation=cv2.INTER_AREA)
        cv2.imshow("press q to quit", frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    cv2.destroyAllWindows()
    cap.release()
